package com.gxuwz.stats.controller;

import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api")
public class FileController {
    @Value("${file.upload-path:./attachment/}")
    private String uploadPath;
    private static final long MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB

    @Autowired
    private UserService userService;

    @PostMapping("/fileUpload")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("year") String year,
            @RequestParam("type") String type,
            @RequestParam(value = "projectLevel", required = false) String projectLevel,
            @RequestParam("username") String username
    ) {
        Map<String, Object> response = new HashMap<>();

        if (file.isEmpty()) {
            response.put("code", 400);
            response.put("error", "文件为空");
            return ResponseEntity.badRequest().body(response);
        }

        if (file.getSize() > MAX_FILE_SIZE) {
            response.put("code", 400);
            response.put("error", "文件大小超过20MB限制");
            return ResponseEntity.badRequest().body(response);
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        if (!isValidFileType(fileExtension)) {
            response.put("code", 400);
            response.put("error", "不支持的文件类型，仅支持图片和PDF");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 根据用户名获取用户信息
            User user = userService.findByUsername(username);
            if (user == null) {
                response.put("code", 400);
                response.put("error", "未找到用户信息");
                return ResponseEntity.badRequest().body(response);
            }

            // 学院名到缩写的映射
            Map<String, String> deptMap = new HashMap<>();
            deptMap.put("电子信息与人工智能学院", "dzxxyrgznxy");
            deptMap.put("宝石与艺术设计学院", "bsyyssjxy");
            deptMap.put("外国语学院", "wgyxy");
            deptMap.put("经济学院", "jjxy");
            deptMap.put("机械与资源工程学院", "jxyzygcxy");
            deptMap.put("教师教育学院", "jsjyxy");
            deptMap.put("文学与传媒学院", "wxycmxy");
            deptMap.put("法学院", "fxy");
            deptMap.put("马克思主义学院", "mkszyxy");
            deptMap.put("管理学院", "glxy");
            deptMap.put("食品与制药工程学院", "spyzygcxy");
            deptMap.put("体育健康学院", "tyjkxy");

            String deptShort = deptMap.getOrDefault(user.getDepartment(), "unknown");

            // 路径拼接
            String relativePath = String.format("%s/%s/%s/", year, deptShort, type);
            Path uploadPathFull = Paths.get(new java.io.File(uploadPath).getAbsolutePath(), relativePath);
            Files.createDirectories(uploadPathFull);

            // 文件名拼接
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH_mm_ss");
            String timestamp = now.format(formatter);

            String fileName;
            if (projectLevel != null && !projectLevel.isEmpty()) {
                fileName = String.format("%s_%s_%s.%s", user.getUserId(), projectLevel, timestamp, fileExtension);
            } else {
                fileName = String.format("%s_%s.%s", user.getUserId(), timestamp, fileExtension);
            }
            Path filePath = uploadPathFull.resolve(fileName);

            // 保存文件
            Files.write(filePath, file.getBytes());

            // 返回相对路径，前端拼接 /attachment/ 即可访问
            response.put("code", 200);
            response.put("path", relativePath + fileName);
            response.put("fileName", fileName);
            response.put("userId", user.getUserId());
            response.put("department", deptShort);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("error", "文件上传失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) return "";
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    private boolean isValidFileType(String extension) {
        return extension.matches("(jpg|jpeg|png|gif|pdf)");
    }

    @GetMapping("/download")
    public void downloadFile(@RequestParam("path") String filePath, HttpServletResponse response) throws IOException {
        // 1. 计算物理路径
        Path absolutePath = Paths.get(new java.io.File(uploadPath).getAbsolutePath(), filePath);
        java.io.File file = absolutePath.toFile();
        if (!file.exists()) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
            response.getWriter().write("文件不存在");
            return;
        }
        // 2. 设置响应头，强制下载
        response.setContentType("application/octet-stream");
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        // 3. 写文件内容
        Files.copy(file.toPath(), response.getOutputStream());
        response.flushBuffer();
    }
}

//package com.gxuwz.stats.controller;
//
//import com.gxuwz.stats.entity.User;
//import com.gxuwz.stats.service.UserService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.HashMap;
//import java.util.Map;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//
//@RestController
//@RequestMapping("/api")
////@CrossOrigin(origins = "http://172.17.3.88:8090", allowCredentials = "true")
//public class FileController {
//    // 使用相对于项目根目录的路径
//    private static final String BASE_UPLOAD_DIR = "attachment";
//    private static final long MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
//
//    @Autowired
//    private UserService userService;
//
//    @PostMapping("/fileUpload")
//    public ResponseEntity<Map<String, Object>> uploadFile(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam("year") String year,
////            @RequestParam("department") String department,
//            @RequestParam("type") String type,
//            @RequestParam(value = "projectLevel", required = false) String projectLevel,
//            @RequestParam("username") String username
//            ) {
////        System.out.println("111="+department);
//        Map<String, Object> response = new HashMap<>();
//
//        if (file.isEmpty()) {
//            response.put("code", 400);
//            response.put("error", "文件为空");
//            return ResponseEntity.badRequest().body(response);
//        }
//
//        if (file.getSize() > MAX_FILE_SIZE) {
//            response.put("code", 400);
//            response.put("error", "文件大小超过20MB限制");
//            return ResponseEntity.badRequest().body(response);
//        }
//
//        // 验证文件类型
//        String originalFilename = file.getOriginalFilename();
//        String fileExtension = getFileExtension(originalFilename);
//        if (!isValidFileType(fileExtension)) {
//            response.put("code", 400);
//            response.put("error", "不支持的文件类型，仅支持图片和PDF");
//            return ResponseEntity.badRequest().body(response);
//        }
//
//        try {
//            // 根据用户名获取用户信息
//            User user = userService.findByUsername(username);
//            if (user == null) {
//                response.put("code", 400);
//                response.put("error", "未找到用户信息");
//                return ResponseEntity.badRequest().body(response);
//            }
//
//            String projectRoot = System.getProperty("user.dir");
//
//            // 学院名到缩写的映射
//            Map<String, String> deptMap = new HashMap<>();
//            deptMap.put("电子信息与人工智能学院", "dzxxyrgznxy");
//            deptMap.put("宝石与艺术设计学院", "bsyyssjxy");
//            deptMap.put("外国语学院", "wgyxy");
//            deptMap.put("经济学院", "jjxy");
//            deptMap.put("机械与资源工程学院", "jxyzygcxy");
//            deptMap.put("教师教育学院", "jsjyxy");
//            deptMap.put("文学与传媒学院", "wxycmxy");
//            deptMap.put("法学院", "fxy");
//            deptMap.put("马克思主义学院", "mkszyxy");
//            deptMap.put("管理学院", "glxy");
//            deptMap.put("食品与制药工程学院", "spyzygcxy");
//            deptMap.put("体育健康学院", "tyjkxy");
//
//            String deptShort = deptMap.getOrDefault(user.getDepartment(), "unknown");
//
//            // 路径拼接（type为必填）
//            String relativePath = String.format("%s/%s/%s/", year, deptShort, type);
//            Path uploadPath = Paths.get(projectRoot, BASE_UPLOAD_DIR, relativePath);
//            Files.createDirectories(uploadPath);
//
//            // 文件名拼接
//            LocalDateTime now = LocalDateTime.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH_mm_ss");
//            String timestamp = now.format(formatter);
//
//            String fileName;
//            if (projectLevel != null && !projectLevel.isEmpty()) {
//                fileName = String.format("%s_%s_%s.%s", user.getUserId(), projectLevel, timestamp, fileExtension);
//            } else {
//                fileName = String.format("%s_%s.%s", user.getUserId(), timestamp, fileExtension);
//            }
//            Path filePath = uploadPath.resolve(fileName);
//
//            // 保存文件
//            Files.write(filePath, file.getBytes());
//
//            // 返回相对路径，添加attachment前缀
//            response.put("code", 200);
//            response.put("path", relativePath + fileName);
//            response.put("fileName", fileName);
//            response.put("userId", user.getUserId());
//            response.put("department", deptShort);
//            return ResponseEntity.ok(response);
//        } catch (IOException e) {
//            e.printStackTrace();
//            response.put("code", 500);
//            response.put("error", "文件上传失败：" + e.getMessage());
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
//        }
//    }
//
//    private String getFileExtension(String fileName) {
//        if (fileName == null || fileName.isEmpty()) return "";
//        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//    }
//
//    private boolean isValidFileType(String extension) {
//        return extension.matches("(jpg|jpeg|png|gif|pdf)");
//    }
//}
